package com.bdbit.ChargingStation.services.impl;

import com.bdbit.ChargingStation.model.TransactionRecord;
import com.bdbit.ChargingStation.services.PaymentService;
import com.bdbit.ChargingStation.services.WXPayService;
import com.bdbit.ChargingStation.services.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private WXPayService wxPayService;

    @Autowired
    private AliPayService aliPayService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    // 模拟数据库存储交易记录
    private final Map<String, TransactionRecord> transactionRecords = new HashMap<>();

    @Override
    public boolean processPayment(String userId, int amount, String deviceId) {
        log.info("处理支付请求 - 用户ID: {}, 金额: {}分, 设备ID: {}", userId, amount, deviceId);
        
        // 在实际系统中，这里会调用第三方支付接口（如支付宝、微信支付）
        // 这里我们模拟支付成功
        
        // 创建交易记录
        TransactionRecord record = new TransactionRecord();
        record.setTransactionId(UUID.randomUUID().toString());
        record.setUserId(userId);
        record.setDeviceId(deviceId);
        record.setAmount(amount);
        record.setStatus("PAID");
        record.setTimestamp(System.currentTimeMillis());
        
        // 保存交易记录
        transactionRecords.put(deviceId, record);
        
        log.info("支付成功 - 交易ID: {}", record.getTransactionId());
        return true;
    }

    @Override
    public boolean processRefund(String deviceId) {
        log.info("处理退款请求 - 设备ID: {}", deviceId);
        
        // 获取交易记录
        TransactionRecord record = transactionRecords.get(deviceId);
        if (record == null) {
            log.warn("找不到设备 {} 的交易记录", deviceId);
            return false;
        }
        
        // 在实际系统中，这里会调用第三方支付接口进行退款
        // 这里我们模拟退款成功
        
        // 更新交易记录状态
        record.setStatus("REFUNDED");
        record.setRefundTimestamp(System.currentTimeMillis());
        
        log.info("退款成功 - 交易ID: {}", record.getTransactionId());
        return true;
    }

    @Override
    public TransactionRecord getTransactionRecord(String deviceId) {
        return transactionRecords.get(deviceId);
    }

    @Override
    public long calculateChargingTime(int amount, int chargingRate, int unitPriceDuration) {
        log.info("计算充电时长 - 金额: {}分, 充电功率: {}W, 单位时长: {}分钟", 
                amount, chargingRate, unitPriceDuration);
        
        // 统一计费标准：1元 = 5分钟
        double amountYuan = amount / 100.0;
        double timeMinutes = amountYuan * 5; // 1元对应5分钟
        long timeSeconds = (long) (timeMinutes * 60);
        
        log.info("计算完成 - 充电时长: {}秒 ({}分钟)", timeSeconds, timeMinutes);
        return timeSeconds;
    }

    @Override
    public boolean refund(String orderId, BigDecimal refundAmount) {
        try {
            // 根据订单ID查询支付方式
            String payType = getPayTypeByOrderId(orderId);
            
            if ("wxpay".equals(payType)) {
                return wxPayService.refund(orderId, refundAmount);
            } else if ("alipay".equals(payType)) {
                return aliPayService.refund(orderId, refundAmount);
            } else {
                log.error("未知的支付方式: {}", payType);
                return false;
            }
        } catch (Exception e) {
            log.error("退款失败: orderId={}, amount={}", orderId, refundAmount, e);
            return false;
        }
    }

    private String getPayTypeByOrderId(String orderId) {
        try {
            String sql = "SELECT pay_type FROM charging_order WHERE order_id = ? OR id = ? LIMIT 1";
            return jdbcTemplate.queryForObject(sql, String.class, orderId, orderId);
        } catch (Exception e) {
            log.error("查询支付方式失败: orderId={}", orderId, e);
            return "wxpay"; // 默认返回微信支付
        }
    }
}